package org.jl.demo.authority.controller.user;

import jakarta.annotation.Resource;
import org.jl.demo.authority.model.po.User;
import org.jl.demo.authority.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/")
    public String index(Model model, @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "5") int size) {
        Pageable pageable = PageRequest.of(page, size);
        Page<User> users = userService.page(pageable);
        model.addAttribute("users", users);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", users.getTotalPages());
        return "/user/index";
    }

    @RequestMapping(name="/user", method=RequestMethod.POST)
    @GetMapping("/add")
    public String addForm(Model model) {
        model.addAttribute("user", new User());
        return "/user/add";
    }

    @PostMapping("/add")
    public String add(@ModelAttribute User user) {
        userService.insert(user);
        return "redirect:/user/";
    }

    @GetMapping("/edit/{id}")
    public String editForm(@PathVariable Integer id, Model model, @RequestParam(defaultValue = "0") int page) {
        model.addAttribute("user", userService.getById(id).orElse(new User()));
        model.addAttribute("currentPage", page);
        return "/user/edit";
    }

    @PostMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, @ModelAttribute User userDetails, @RequestParam(defaultValue = "0") int page) {
        userService.update(id, userDetails);
        return "redirect:/user/?page=" + page;
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/user/";
    }
}
